<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 安全责任指标考核记录 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基础信息"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''" @selectOrg="selecOrg"> </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="打分项"></title-name>
          <s-table ref="table" tableLayout="fixed" size="default" rowKey="key" :columns="columns" :data="loadData" :alert="true" show-size-changer show-quick-jumper :showPagination="false">
            <template slot="reviseScore" slot-scope="text, record">
              <BaseInputNumber
                :precision="2"
                :disabled="editModel == 0"
                :disabledValue="record.sysScore"
                :min="record.checkTypeCode == '1008' || record.checkTypeCode == '1003' ? undefined : 0"
                :max="record.checkTypeCode == '1008' || record.checkTypeCode == '1003' ? 0 : record.allScore"
                v-model="record.reviseScore"
                @change="changeReviseScore(record)"
              ></BaseInputNumber>
            </template>
            <template slot="reviseRemark" slot-scope="text, record">
              <div :class="!record.reviseScore ? '' : 'form-item'">
                <BaseInput :disabled="editModel == 0" v-model="record.reviseRemark"></BaseInput>
              </div>
            </template>
          </s-table>
        </a-card>

        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')">提交</a-button>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import api from '@/api/safetySupervision/base/inspectionTemplate.js'

import moment from 'moment'
const columns = [
  {
    title: '考核项目',
    dataIndex: 'checkType'
  },
  {
    title: '扣分标准',
    dataIndex: 'deductPoints'
  },
  {
    title: '满分',
    dataIndex: 'allScore'
  },
  {
    title: '系统得分',
    dataIndex: 'sysScore'
  },
  {
    title: '修订得分',
    dataIndex: 'reviseScore',
    scopedSlots: { customRender: 'reviseScore' }
  },
  {
    title: '修订原因',
    dataIndex: 'reviseRemark',
    scopedSlots: { customRender: 'reviseRemark' }
  },
  {
    title: '实得分',
    dataIndex: 'realScore',
    scopedSlots: { customRender: 'realScore' }
  }
]

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),

  data() {
    this.columns = columns

    return {
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增

      form: {}, // 表单

      initData: {},
      id: '',

      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },

      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.checkList || []
          })
        })
      },

      init: false, // 初始化控件
      titles: ['安全责任指标考核记录查看', '安全责任指标考核记录编辑', '安全责任指标考核记录新增']
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['安全责任指标考核记录查看', '安全责任指标考核记录编辑', '安全责任指标考核记录新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getDetails()
    } else {
      this.getDefault()
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
        this.form.creatorName = this.$userInfo().name
        this.form.checkDept = this.$userInfo().currentPost.deptName
        this.form.checkPost = this.$userInfo().employee.posts.filter((e) => e.code == this.$userInfo().currentPost.postCode)[0].name
        this.form.checkMonth = moment().format('YYYY-MM-DD')
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: false,
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'checkName',
          type: 'BaseInput',
          disabled: true,
          label: '人员'
        },
        {
          keyName: 'checkMonth',
          type: 'a-month-picker',
          disabled: true,
          label: '考核月份',
          attrs: {
            valueFormat: 'YYYY-MM'
          }
        },
        {
          keyName: 'realScore',
          type: 'BaseInput',
          disabled: true,
          label: '总分'
        }
      ]
    }
  },
  methods: {
    selecOrg(val) {
      if(val.length > 1) {
        this.form.branchCompanyId = val[val.length - 2].orgId
      }
    },
    changeReviseScore(record) {
      if (record.reviseScore) {
        record.realScore = record.reviseScore
      } else {
        record.realScore = record.sysScore
      }
      this.$refs.table.loadData()
      this.form.realScore = 0
      this.form.checkList.forEach((i) => {
        this.form.realScore += i.realScore
      })
    },
    getDetails() {
      this.loading = true

      api
        .getRecord({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
          this.$refs.table.loadData()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag1 = true
      let flag2 = true

      this.$refs.ruleForm.validate((e) => {
        flag1 = e
      })
      this.form.checkList.forEach((e) => {
        if (e.reviseScore && e.reviseScore != 0 && !e.reviseRemark) {
          flag2 = false
        }
      })
      if (!flag2) {
        this.$message.warning('请完善表格数据')
        return false
      }

      if (flag1 && flag2) {
        return true
      } else {
        return false
      }
    },
    okSubmit(status) {
      this.loading = true
      this.loadingBtn[status] = true

      let form = this.$clone(this.form)
      form.auditStatus = status

      // form.employeeId = this.$userInfo().employee.id
      // form.userId = this.$userInfo().id
      // form.checkName = this.$userInfo().name
      // let req = [api.updatePerson, api.addPerson][this.editModel - 1] // 根据操作切换url地址
      api
        .updateRecord(form)
        .then(() => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }

      this.okSubmit(status)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
